package com.example.wm.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.wm.common.R;
import com.example.wm.entity.Employee;
import com.example.wm.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/employee")
//无用 练习文件
public class EmployeeController {


        @Resource
        private EmployeeService employeeService;
        Boolean a;
        @Value("${reggie.path}")
          private String basepath;

        @PostMapping("/login")
// 需要在目标方法上添加@Transactional注解，将事务交给spring管理
        //登录
        @Transactional
        public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){

           String passwords=employee.getPasswords();
           //加密
           passwords= DigestUtils.md5DigestAsHex(passwords.getBytes());
                LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>();
                queryWrapper.eq(Employee::getName,employee.getName());
                Employee emp=employeeService.getOne(queryWrapper);
                   log.info("开始登录--------");
            if (emp == null) {
                return R.error("等陆失败");

            }
            if (!emp.getPasswords().equals(passwords)){
               a= !emp.getPasswords().equals(passwords);
               System.out.println(a);
                return  R.error("密码错误");
            }
//            if (emp.getStatus()==0){
//                return R.error("账号已禁用");
//            }

          request.getSession().setAttribute("employee",emp.getId());
              return  R.success(emp);

//              return null;



        }

         @PostMapping("/logout")
    //          退出登录
         public  R<String> logout(HttpServletRequest request){
                               request.getSession().removeAttribute("employee");
                               return R.success("退出成功");
                   }
           @Transactional
             @PostMapping
//添加人员
           public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
             log.info("{}",employee);
             employee.setPasswords(DigestUtils.md5DigestAsHex("123456".getBytes()));
             employee.setUpdate_time(LocalDateTime.now());


               UUID uuid  =  UUID.randomUUID();
               String s = UUID.randomUUID().toString();
               s = s.replace("-", "");
               int num = s.hashCode();
               num = num < 0 ? -num : num;
               s = String.valueOf(num);
               employee.setId(Integer.valueOf(s));

             employeeService.save(employee);
//             employeeService.updateById(employee);
                   return  R.success("新增成功");
         }

    //分页查询
    @PostMapping("/page")
    @Transactional
    public R<Page> page(int page, int pageSize,String name) {
        Page<Employee> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.orderByAsc(Employee::getSort);
        queryWrapper.like(Strings.isNotEmpty(name),Employee::getName,name);
        queryWrapper.orderByAsc(Employee::getUpdate_time);
       employeeService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }
    //根据员工id查询信息
    @PostMapping("/ids")
    public  R<Employee> getById(@RequestBody Employee employee){
            Employee ee=employeeService.getById(employee.getId());
            if(ee!=null){
                return R.success(ee);
            }
            return null;
    }
    //上传文件
    @PostMapping("/files")
    public R<String> upload(MultipartFile file){
        if (file.isEmpty()){
            return R.error("");
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名："+fileName);
        //获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("文件后缀名："+suffixName);
        //设置文件名称
        String fileNames =UUID.randomUUID().toString()+suffixName;

        File dest = new File(basepath+fileNames);
        //检测是否存在该目录
        if (!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try {
            //写入文件
            file.transferTo(dest);
            return R.success(fileNames);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileNames);

    }
    //下载
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
//输入流
        FileInputStream streams=new FileInputStream(new File(basepath+name));
//输出流
        response.setContentType("image/jpeg");
        ServletOutputStream outputStream=response.getOutputStream();
        int lent=0;
        byte[] bytes=new byte[1024];
        streams.read(bytes);
        while ((lent=streams.read(bytes))!=-1){
            outputStream.write(bytes,0,lent);
            outputStream.flush();
        }
        //关闭流
        streams.close();
        outputStream.close();
    }




}

